package com.xinyue.chat.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;

public class ChatDispatchHandler extends ChannelInboundHandlerAdapter {

	private static Logger logger = LoggerFactory.getLogger(ChatDispatchHandler.class);
	private ApplicationContext applicationContext;
	private ChannelGroup channelGroup;
	private String nickName;

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		channelGroup = applicationContext.getBean(ChannelGroup.class);
		channelGroup.add(ctx.channel());
		ctx.fireChannelActive();
	}

	public ChatDispatchHandler(ApplicationContext context) {
		this.applicationContext = context;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (!(msg instanceof MessageRequest)) {
			ctx.fireChannelRead(msg);
		} else {
			MessageRequest message = (MessageRequest) msg;
			int messageId = message.getHeader().getMessageId();
			logger.debug("收到聊天请求：{}",messageId);
			if (MessageIDEnum.ENTER_CHAT_ROOT.isMatch(messageId)) {
				// 进入聊天室
				nickName = message.getBody().getString("msg");
				JSONObject data = new JSONObject();
				String value = "欢迎[" + nickName + "]进入聊天室";
				data.put("msg", value);
				MessageResponse response = new MessageResponse(message);
				response.setResponseBody(data);
				ctx.writeAndFlush(response);
				this.pushMessage(data, MessageIDEnum.ENTER_CHAT_ROOT, (channel) -> {
					return ctx.channel() != channel;
				});
			} else if (MessageIDEnum.SEND_CHAT_MESSAGE.isMatch(messageId)) {
				// 转发聊天信息
				MessageResponse response = new MessageResponse(message);
				response.setResponseBody(message.getBody());
				ctx.writeAndFlush(response);
				this.pushMessage(message.getBody(), MessageIDEnum.SEND_CHAT_MESSAGE, (channel) -> {
					return ctx.channel() != channel;
				});
			} else {
				ctx.fireChannelRead(msg);
			}
		}

	}

	private void pushMessage(JSONObject message, MessageIDEnum messageIdEnum, ChannelMatcher matcher) {
		MessageRequest request = new MessageRequest();
		MessageHeader header = new MessageHeader();
		header.setMessageId(messageIdEnum.getMessageId());
		header.setMessageType(2);
		header.setServerSendTime(System.currentTimeMillis());
		request.setHeader(header);
		MessageResponse response = new MessageResponse();
		response.setResponseBody(message);
		response.setHeader(header);
		channelGroup.writeAndFlush(response, matcher);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.error("服务器异常", cause);
	}
}
